package com.dnjn.happiness.emo.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.emo.domain.Ranklist;
import com.dnjn.happiness.emo.domain.vo.RanklistVO;
import com.dnjn.happiness.emo.mapper.RanklistMapper;
import com.dnjn.happiness.emo.service.IRanklistService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Objects;

/**
 * 每日打卡榜单ranklistService业务层处理
 *
 * @author amber
 * @date 2024-03-05
 */
@Service
public class RanklistServiceImpl extends ServiceImpl<RanklistMapper, Ranklist> implements IRanklistService {

    //    @Async
    @Override
    public boolean updateRecord(Long userId, String nickName, boolean hasClockInYesterday) {
        LocalDate today = LocalDate.now();

        Ranklist po = lambdaQuery()
                .eq(Ranklist::getUserId, userId)
                //.eq(Ranklist::getLastOperDate, today)
                .eq(Ranklist::getDeleted, "0")
                .oneOpt()
                .orElse(new Ranklist().setUserId(userId).setNickName(nickName).setTotalCount(0).setLastingCount(0));

        // 连续打卡量
        LocalDate lastOperDate = po.getLastOperDate();
        boolean hasOprtToday = false;
        if (Objects.nonNull(lastOperDate) && today.compareTo(lastOperDate) == 0) {
            hasOprtToday = true;
        }

        if (!hasOprtToday) {
            po.setTotalCount(po.getTotalCount() + 1);   //总打卡量

            po.setLastOperDate(today);
            if (hasClockInYesterday) {
                po.setLastingCount(po.getLastingCount() + 1);
            } else {
                //re-count
                po.setLastingCount(1);
            }
        }

        return saveOrUpdate(po);
    }

    @Override
    public Page<RanklistVO> selectPage(Page page) {

        return baseMapper.selectPageX(page);
    }

    @Override
    public Ranklist getByUserId(Long userId) {
        return lambdaQuery().eq(Ranklist::getUserId, userId).one();
    }
}
